import matplotlib.pyplot as plt
import numpy as np
from sklearn.neighbors import KNeighborsRegressor
from sklearn.model_selection import train_test_split
x=np.array([[182],[178],[170],[168],[165],[162],[158],[154],[149],[144]])
y=np.array([[113],[105],[86],[83],[86],[74],[72],[45],[49],[43]])
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3,random_state=0)
k_range=range(2,8)
k_error=[]
for k in k_range:
    model=KNeighborsRegressor(n_neighbors=k)
    model.fit(x_train,y_train)
    scores=model.score(x_test,y_test)
    k_error.append(1-scores)
plt.rcParams['font.sans-serif']='Simhei'
plt.plot(k_range,k_error,'r-')
plt.xlabel('k的取值')
plt.ylabel('预测误差率')
plt.show()
model=KNeighborsRegressor(3)
model.fit(x_train,y_train)
plt.xlabel('身高/cm')
plt.ylabel('体重/kg')
plt.rcParams['font.sans-serif']='Simhei'
plt.axis([140,190,40,140])
plt.scatter(x,y,s=60,c='k',marker='o')
plt.plot(x,model.predict(x),'r-')
plt.show()
pred=model.predict([[173]])
print("身高173cm的学生体重与预测为",pred)